<template>
    <div id="p_habit" class="p_task">        
       <scroller lock-x scrollbar-y use-pullup :pullup-config="pullupConfig2" :height="scrollHeight" ref="habitScrol" v-model="pullStatus" @on-pullup-loading="loadNext" :scroll-bottom-offset="200">
         <group class="group0">
            <div v-if="lifes.length==0" style="text-align:center;" ><img src="/static/z39h5/img/none.png" width="200" /></div>
            <swipeout>
                <swipeout-item v-if="index<pageShowNum" @on-open="actionOpen(item, index,2)" v-for="(item, index) in lifes" :key="index" ref="actionHabit" >
                    <div slot="right-menu">  <!-- v-if="!item.id"-->
                        <swipeout-button @click.native="onDelRep(item,index)" type="primary">删除习惯</swipeout-button>
                        <swipeout-button v-if="item.id" @click.native="onCancel(item,index)" type="warn">取消任务</swipeout-button>
                    </div>
                    <div slot="left-menu">
                        <swipeout-button type="primary">{{item.state!='done'?'完成':'取消完成'}}</swipeout-button>
                    </div>
                    <div slot="content" class="vux-1px-t">
                        <t-cell @click.native="openBtns(item)" :title="showTaskTitle(item)" :tagTop="item" :inline-desc="doshowDesc(item,index)" v-bind:class="{task_going:item.state=='started',task_done:item.state=='done',task_toggle:item.state=='toggle',task_cancle:item.state=='cancelled',task_curr: taskCurr == item}">
                            <img slot="icon" :src="item.img || '/static/z39h5/img/logoc.png'" />
                        </t-cell>
                    </div>
                </swipeout-item>
            </swipeout>
        </group>
      </scroller>
      <!--<x-button :style="{bottom:(isNavShow?62:06)+'px'}" class="taskAdd" @click.native="onTaskAdd" type="primary" ><span style="font-size:22px;padding-right: 8px;" class="icon iconfont icon-tianjia2"></span></x-button>
      <task-add :show="showTaskAdd" :ext="taskAddExt" v-on:exts="habitsChange" v-on:toVisible="taskAddVis" type="habit" :exts="habitsBtn"></task-add>
	  --> 

      <actionsheet v-model="showBtn" :menus="doBtns" @on-click-menu="doHabit"></actionsheet>
    </div>
</template>
<script>
import moment from 'moment';
import _ from "../../../static/jslib/underscore-min.js";
import Vue from 'vue';
import TCell from "../t-cell/index.vue"
import TaskAdd from "../TaskAdd";

import api from '../../api';
import {
    mapState,
    mapActions
} from 'vuex'

const FLAG_TASK = ["created", "started", "done", "toggle", "cancelled", "due", "used", "usedCalc", "timeDiff"]; //"need",

import { taskAndTag } from "../mixin";
import { help } from "../mixinApp";
import { logic } from "../mixinTaskLogic";
let defaultAct = {img:"/static/z39h5/img/logoc.png",title: "",duration: "",desc: ""};
let lifeFlagArr =[{name:"自定义",value:"custom",img:'logoc'},
                {name:"醒",value:"wakeup",img:'wakeup'},
                {name:"起床",value:"getup",img:'getup'},
                {name:"洗漱1",value:"wash1",img:'wash'},
                {name:"洗澡",value:"bath",img:'bath'},
                {name:"厕所",value:"wc",img:'wc'},
                {name:"早饭",value:"breakfast",img:'eat'},
                {name:"录音",value:"tape",img:'record'},
                {name:"学习",value:"study",img:'study'},
                {name:"去上班",value:"gowork",img:'gowork'},
                {name:"上班",value:"workStart",img:'workStart'},
                {name:"工作准备",value:"workReady",img:'workReady'},
                {name:"腹肌撕裂者T4",value:"health",img:'health'},
                {name:"午饭",value:"lunch",img:'eat'},
                {name:"卡通",value:"cartoon",img:'cartoon'},
                {name:"晚饭",value:"dinner",img:'eat'},
                {name:"下班",value:"workEnd",img:'workEnd'},
                {name:"回家",value:"gohome",img:'gohome'},
                {name:"洗漱2",value:"wash2",img:'wash'},
                {name:"睡觉",value:"sleep",img:'sleep'}] ;


import {
    Tab,
    TabItem,
    TransferDomDirective as TransferDom,
    Toast,
    Swipeout,
    SwipeoutItem,
    SwipeoutButton,
    XButton,
    PopupPicker,
    Group,
    Picker,
    Cell,
    Box,
      XInput,
      XTextarea,Flexbox, FlexboxItem,Datetime,Actionsheet,
    ButtonTab,    ButtonTabItem,
    Checker,
    CheckerItem,    
    Scroller,
    Sticky
} from 'vux'

export default {
    directives: {
        TransferDom
    },
    components: {
    Tab,TCell,TaskAdd,
    TabItem,
        Toast,
        Swipeout,
        SwipeoutItem,
        SwipeoutButton,
        XButton,
    PopupPicker,
    Group,
    Picker,
        Cell,
    Box,
      XInput,
      XTextarea,Flexbox, FlexboxItem,Datetime,Actionsheet,
    ButtonTab,    ButtonTabItem,
    Checker,
    CheckerItem,
    Scroller,
    Sticky
    },    
    mixins: [taskAndTag,logic,help],    
    computed: {
        // lifes: function() {
        //     let tasks = this.doRender();
        //     return tasks ;
        // },
        ...mapState({
            isNavShow: state => state.vux.isNavShow,
            uid: state => state.vux.uid,
            taskAll: state => state.z39.taskAll,
            tagDic: state => state.z39.tagDic,
            repeat: state => state.z39.repeat,
        })
    },
    watch: {        
        "uid":function(){
            this.getInitData();
        },
        "repeat":function(){
            this.doRender();
        },
        "taskAll":function(){
            this.pageIndex = 1 ;
            this.doRender();
        },
    },
    activated () {
    },
    created() {
        var tmp = localStorage.getItem('habitTmp');
        if(tmp) this.habitTmpObj = JSON.parse(tmp);
        this.scrollHeight = this.isNavShow?"-97":"-42";

        var temp= [] , obj = {} ;
        var len = lifeFlagArr.length ;
        for(var i=0;i<= len-1 ;i++){
            var item = lifeFlagArr[i] ;
            obj[item.value] = item.img ;  // item.value == tag.key , 
            temp.push({title:item.name , desc:"" , duration:"",img: '/static/z39h5/img/'+ item.img +'.png'});
        }
        this.actionLifeArr = temp ;
        this.imgDic = obj ;
        // this.doRender();
        this.initPage();
        console.log("Habit.vue created")
        setTimeout(()=>{
            this.taskAddExt = {tags:{repeat:"D",life:""}} ;
        },1000)
		//this.$store.commit({ type: "z39/addTaskExt", value: {tags:{repeat:"D",life:""}} });
        this.$vux && this.$vux.bus && this.$vux.bus.$on('habitsChange', this.habitsChange)
    },
    mounted: function() {
    },
    methods: {        
        getInitData(){
            this.initPage();
        },
        initPage(){
			// if( this.uid == 0 ) return ;
            console.log("initPage")
            let day = moment().format("YYYY-MM-DD");
            api.habitGet({day,has:true}).then(data=>{
                if(data.errno !=0) return this.$vux.toast.show({text: data.errmsg ,type: 'warn'});
                data = data.data ;
                this.habitSaveData = data ;
                var obj = {id:data.id,tmp:data.tmp} ;
                this.habitTmpObj = obj ;
                localStorage.setItem('habitTmp', JSON.stringify(obj) );
                this.$store.commit({ type: "z39/repeat", value: data.repeat });
                this.$store.commit({ type: "z39/taskToDB", tasks: data.tasks, act: "add" });
            })
        },
        onCancel( item, index) {
            // console.log(item);
            if(!item.id) return ;
            this.doTaskEdit(item,"cancelled",moment().format("YYYY-MM-DD HH:mm"));
        },
        onDelRep(item,index){
            if(item.sid) {;
                var ids = this.habitTmpObj.tmp.split(",") ;
                var index = ids.indexOf(item.sid+"") ;
                if(index == -1) return this.$vux.toast.show({text:'找不到数据'});
                ids.splice(index,1);
                var tmp = ids.join(",") ;
                var id = this.habitTmpObj.id;
                var sdata = {id,tmp} ;
                api.habitSet(sdata).then(data=>{
                    // this.habitTmpObj.id = data.data ;
                    this.habitTmpObj.tmp = tmp ;
                    localStorage.setItem('habitTmp', JSON.stringify(sdata) );
                    this.$store.commit("z39/repeatDel", {value:item.sid});
                    this.clearClock({id:item.sid},"clear");
                })
            }
        },
        goTask(item,index){ // 进入任务详情

        },
        getHabitKey(task){
            let res="";
            if(!task.tags) return "" ;
            var temp = [];
            for(var key in task.tags){
                if(FLAG_TASK.indexOf(key)==-1) temp.push(key);
            }
            res = temp.sort().join("_") + task.title; // +task.id + task.sid ;
            return res ;
        },
        doRender(){
            console.log("doRender");
            let today = moment().format("YYYY-MM-DD") ;
            let doneDic = {};
            let tagkeys ,imgkey , imgUrl,tkey ;
            let dones = this.taskAll.filter(task=> {
                var val = task.tags && task.tags.life != undefined &&task.tags.created&& task.tags.created.indexOf(today) == 0 ;
                if(val){
                    tkey = this.getHabitKey(task);
                    doneDic[tkey] = task ;
                }
                return val;
            }) ;
            let temps = this.repeat.filter(task=> {return task.tags && task.tags.life != undefined } ) ;
            let keys = _.keys( this.imgDic ) ;
            var len = temps.length ,tempkey ;
            let tasks = [];
            let taskDic = {};
            for(var i=0;i<= len-1 ;i++){
                var item = temps[i] ;
                tkey = this.getHabitKey(item);
                if(doneDic[tkey] !=undefined){
                    let temp = doneDic[tkey];
                    temp.sid = item.sid ;
                    item = temp ;
                }
                tagkeys = _.keys( item.tags ) ;
                imgkey = _.intersection(keys,tagkeys) ; 
                tempkey = imgkey.length > 0 ? imgkey[0] :"custom" ;
                imgUrl = this.imgDic[ tempkey ] ;
                item.img = '/static/z39h5/img/'+ imgUrl +'.png' ;
                taskDic[item.sid] = item ;
            }
            if(!this.habitTmpObj.tmp) return this.lifes=[] ;
            // console.log("showindex:",this.habitTmpObj.tmp,this.repeat)
            // tasks.push(item);
            let ids = this.habitTmpObj.tmp.split(",");
            let task;
            var btns =[];
            this.showIndexDefault = 0 ;
            ids.map(id=>{
                task = taskDic[id] ;
                if(task) {
                    tasks.push(task);
                    btns.push({id:task.sid,title:task.title});
                    if(task.state!="") this.showIndexDefault = tasks.length ;
                }
            })
            // console.log("habit tasks:",tasks.length,this.repeat);
            this.lifes = tasks ;
            // this.habitsBtn = btns ;
            //this.$vux && this.$vux.bus && this.$vux.bus.$emit('taskAddExts', btns);
            this.pageTotal = tasks.length / this.pageNumOne ;
            if(this.pageTotal <= this.pageIndex){
                setTimeout(() => {this.$refs.habitScrol.disablePullup(),console.log("disablePullup",this.pageTotal,this.pageIndex)}, 100)
            }else{
                setTimeout(() => {this.$refs.habitScrol.enablePullup(),console.log("enablePullup",this.pageTotal,this.pageIndex)}, 100)
            }
            this.$nextTick(() => {
                this.$refs.habitScrol.reset()
            })
            return tasks ;
        },
        onTaskAdd(){
            
            this.showTaskAdd = true ;
        },
        taskAddVis(val){
            this.showTaskAdd = val ;
        },
        habitsChange(obj){
            let {arr,task} = obj ;
            var temps = [];
            arr.map(item=>{
                temps.push(item.id);
            })
            var tmp = temps.join(",");
            var id = this.habitTmpObj.id ;
            var sdata = {id,tmp} ;
            api.habitSet(sdata).then(data=>{
                console.log("tmp:",sdata,data);
                this.habitTmpObj.id = data.data ;
                this.habitTmpObj.tmp = tmp ;
                this.habitSaveData.id = data.data ;
                this.habitSaveData.tmp = tmp ;
                this.$store.commit({ type: "z39/repeatAdd", value: task });
            })
            // 
            console.log("tmp:",tmp);
        },
        doTaskAdd(){
            if( this.taskTitle == "") return ;
            let data = {title:this.taskTitle} ;            
            data.desc = this.taskDesc || "";            
            data.state = "weekend" ;
            // let tags = {created:moment().format('YYYY-MM-DD HH:mm'),weekend:""} ;
            // this.taskAdd(data, tags).then(data => { this.resetInput() });
        },
        onEditTask(item,index,state){
            switch(state){
                case "done":

                    break;
                case "undo":

                    break;
                default:
                    console.error("onEditTask:",state);
            }
        },
        actionOpen(item,index,option){            
            let dir = "" , target , arrIndex = index ;
            target = this.$refs.actionHabit[index] ;
                dir = target.direction ;
            if( dir == "left"){
                if(!item.id){
                    let tags = {created:moment().format('YYYY-MM-DD'),done:moment().format("YYYY-MM-DD HH:mm"),life:""} ;
                    tags = Object.assign(tags,item.tags);
                    if(tags.due && tags.due.length>10){
                        tags.created +=tags.due.substr(10);
                    }
                    delete tags.due ;
                    delete tags.repeat ;
                    let sdata ={title:item.title,desc:item.desc,state:"done",sid:item.sid};
                    this.taskAdd(sdata, tags).then(data=>{
                        this.clearClock({id:item.sid},"clear");
                    });
                }else if( item.state == "done"){
                    this.doTaskEdit(item,"");
                }else{
                    this.doTaskEdit(item,"done",moment().format("YYYY-MM-DD HH:mm"));
                }
                setTimeout(() => {
                    target.close();
                }, 200);                
            }
        },
        clickAdd(){
            this.weekEdit=true ;
            this.resetInput(); 
        },
        resetInput(){
            this.taskTitle = "";
            this.taskDesc = "" ;
        },
        getData: function() {
            
        },
        loadNext(){
            if( this.pageIndex < this.pageTotal ){
                this.pageIndex ++ ;
                this.pageShowNum = this.pageIndex * this.pageNumOne ;
                console.log("pageShowNum",this.pageShowNum) ;
                this.$refs.habitScrol.donePullup() ;
            }
			this.checkClosePullup();
        },
		checkClosePullup(){
            this.$refs.habitScrol.reset();
			if( this.pageIndex >= this.pageTotal){
				setTimeout(() => {
					this.$refs.habitScrol.disablePullup();
                    console.log("disablePullup")
				}, 100)	
			}
		},
        openBtns(item){
            this.doBtns = this.getTaskBtns(item,2);
            this.showBtn = true ;
            this.taskCurr = item ;            
        },
        doHabit(key, item) {
            if( item == undefined) return ;//点击取消. 
            let task = this.taskCurr;      
            if(item.value=="info") return this.$vux.toast.show({text:"暂未开放",type: 'warn'});
            if(!task.id && item.value != "cancelled"){
                let tags = {created:moment().format('YYYY-MM-DD'),life:""} ;
                let value = moment().format("YYYY-MM-DD HH:mm");
                tags[item.value] = value;
                if(task.tags.due && task.tags.due.length>10){
                    tags.created +=task.tags.due.substr(10);
                }
                tags = Object.assign(tags,task.tags);
                delete tags.repeat ;
                delete tags.due ;
                let sdata ={title:task.title,desc:task.desc,state:item.value,sid:item.sid};
                this.taskAdd(sdata, tags);
                return ;
            }else if(!task.id && item.value == "cancelled"){
                return ;
            }
            this.doClickTask(item.value,task);
            // this.chooseEdit(key,item);
        },
        doshowDesc(item, index) {
          var tags = item.tags;
          var diff = index - this.showIndexDefault;
          if (!item.state && (diff != 0 && diff != 1)) return "";
          return  this.showTaskDesc1(item);
        },
        ...mapActions([
            
        ])
    },
    data() {
        return {
            actionLifeArr:[],
            showBtn:false,
            doBtns:[],
            showMonth:'',
            taskCurr: null ,
            taskAddExt:{},
            habitsBtn:[],
            habitTmpObj:{},
            lifes:[],
            habitSaveData:{},   //协议缓存导致的问题.
            showTaskAdd:false,
            showIndexDefault:0, //显示默认数据的任务索引
            imgDic:{},
            weekEdit:false ,
            taskTitle:"",
            taskDesc:"",
            pageIndex: 1 ,
            pageTotal: 2 ,
            pageShowNum:15,
            pageNumOne: 15 ,
              pullupConfig2: {
                content: '上拉加载更多',
                downContent: '松开进行加载',
                upContent: '上拉加载更多',
                loadingContent: '加载中...'
              },
            pullStatus: {
              pullupStatus: 'disabled'
            },
            scrollHeight: "-97" , //
        }
    }
}

</script>
<style scoped>

.day-item {
  border: 1px solid #ececec;
  padding: 5px 15px;
}
.day-item-selected {
  border: 1px solid green;
}
</style>
<style>
#p_habit .weui-search-bar:before {
    height: 0;
    border-top: 0;
}
/*#p_task .vux-tab .vux-tab-item{
    background: #fff;
}*/
#p_habit .day  .vux-tab-selected {
    background: #eee;
    border-radius: 4px;
}
#p_habit .weui-cell .weui-cell__hd{
    /*background:#ffffff url(../../../static/z39h5/img/logobg.png) no-repeat fixed top ;*/
}
</style>
